﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Collections;
using System.IO;
using CalemShop.Forms;
using CalemShop.Classes;
using System.Media;
namespace CalemShop
{
    public partial class FrmInputStock : FrmBaseDock
    {
        private DataTable stock = new System.Data.DataTable("shop_stock");
        private AutoCompleteStringCollection itemNameCollection = new AutoCompleteStringCollection();
        private AutoCompleteStringCollection itemSizeCollection = new AutoCompleteStringCollection();
        private AutoCompleteStringCollection itemColorCollection = new AutoCompleteStringCollection();
        private AutoCompleteStringCollection itemSupplierCollection = new AutoCompleteStringCollection();
        private AutoCompleteStringCollection itemPriceCollection = new AutoCompleteStringCollection();
        private AutoCompleteStringCollection itemGenderCollection = new AutoCompleteStringCollection();
        private AutoCompleteStringCollection itemTypeCollection = new AutoCompleteStringCollection();
        private Dictionary<string, int> typeMap = new Dictionary<string, int>();
        private bool startSelectCell = false;
        private Point startSelectPoint = new Point(0, 0);
        private Color defaultCellColor = Color.Black;
        private static bool loadSupplierAndColor = false;
        private long lastAutoKey = 0;
        private long currentAutoKey = 0;
        private bool ignoreCellValueChanged = false;
        private SoundPlayer sound = null;
        public FrmInputStock()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            sound = new SoundPlayer(RuntimeData.GetSoundCompletePath());
        }

        public FrmInputStock(FrmCalemShop shop)
            : base(shop)
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            listBranch.Items.AddRange(RuntimeData.GetCalemBranchList());
            sound = new SoundPlayer(RuntimeData.GetSoundCompletePath());
        }

        private void FrmInputStock_Load(object sender, EventArgs e)
        {
            listBranch.Items.AddRange(RuntimeData.GetCalemBranchList());
            stock.Columns.Add("option", Type.GetType("System.String"));
            stock.Columns.Add("autoKey", Type.GetType("System.Int32"));
            stock.Columns.Add("itemId", Type.GetType("System.String"));
            stock.Columns.Add("itemName", Type.GetType("System.String"));
            stock.Columns.Add("gender", Type.GetType("System.String"));
            stock.Columns.Add("amount", Type.GetType("System.Int32"));
            stock.Columns.Add("size", Type.GetType("System.String"));
            stock.Columns.Add("color", Type.GetType("System.String"));
            stock.Columns.Add("price", Type.GetType("System.Int32"));
            stock.Columns.Add("cost", Type.GetType("System.Int32"));
            stock.Columns.Add("giasi", Type.GetType("System.Int32"));
            stock.Columns.Add("supplier", Type.GetType("System.String"));
            stock.Columns.Add("type", Type.GetType("System.String"));
            stock.Columns.Add("isOk", Type.GetType("System.String"));

            bindingSource.DataSource = stock;
            bindingSource.ResetBindings(true);
            DataTable tb = Database.getItemType();
            foreach (DataRow r in tb.Rows)
            {
                string typeName = r["typeName"].ToString().ToLower();
                int typeId = Int32.Parse(r["typeId"].ToString());
                if (!typeMap.ContainsKey(typeName))
                {
                    typeMap.Add(typeName, typeId);
                }

                itemTypeCollection.Add(typeName);
                if (typeName.Equals("áo"))
                {
                    itemTypeCollection.Add("ao");
                    typeMap["ao"] = typeId;
                }
                else if (typeName.Equals("đầm"))
                {
                    itemTypeCollection.Add("dam");
                    typeMap["dam"] = typeId;
                }
                else if (typeName.Equals("đồ bộ"))
                {
                    itemTypeCollection.Add("do bo");
                    typeMap["do bo"] = typeId;
                }

                contextTypeMenu.Items.Add(typeName);
            }


            itemGenderCollection.AddRange(new string[] { "T", "G" });
            contextMenuGender.Items.Add("T");
            contextMenuGender.Items.Add("G");
            giasi.Visible = mnCheckGiasi.Checked;
            cost.Visible = mnCheckCost.Checked;
            grid.Focus();
            LockWaitOrRelease(true);
            listBranch.Enabled = true;
        }


        private void grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            TextBox prodCode = e.Control as TextBox;
            if (prodCode != null)
            {
                int index = grid.CurrentCell.ColumnIndex;
                AutoCompleteStringCollection collection = getAutoCompleteCollectionByColumnIndex(index);
                if (index == 3 || index == 5 || index == 6 || index == 11)
                {
                    prodCode.AutoCompleteMode = AutoCompleteMode.Suggest;
                }
                else
                {
                    prodCode.AutoCompleteMode = AutoCompleteMode.Append;
                }
                prodCode.AutoCompleteCustomSource = collection;
                prodCode.AutoCompleteSource = AutoCompleteSource.CustomSource;

            }
        }

        private AutoCompleteStringCollection getAutoCompleteCollectionByColumnIndex(int index)
        {
            AutoCompleteStringCollection collection = null;
            switch (index)
            {
                case 2:
                    // Item name:
                    collection = itemNameCollection;
                    break;
                case 3:
                    // Type:
                    collection = itemTypeCollection;
                    break;

                case 5:
                    // color:
                    //collection = itemColorCollection;
                    collection = Database.colorCollection;
                    break;

                case 6:
                    // size:
                    collection = itemSizeCollection;
                    break;
                case 7:
                case 8:
                case 9:
                case 10:
                    collection = itemPriceCollection;
                    break;
                case 11:
                    // supplier:
                    collection = Database.supplierCollection;
                    break;
            }

            return collection;
        }

        private void newRow()
        {
            if (stock.Rows.Count > 30)
            {
                MessageBox.Show("Bạn nên save lại dữ liệu an toàn trước khi tiếp tục thêm sản phẩm mới");
                return;
            }

            DataRow r = stock.NewRow();
            r["option"] = "Xóa";
            r["autoKey"] = currentAutoKey;
            r["amount"] = 1;
            r["cost"] = 0;
            r["price"] = 0;
            r["giasi"] = 0;
            r["supplier"] = "";
            r["itemName"] = "";
            r["color"] = "";
            r["size"] = "";
            r["isOk"] = "false";
            stock.Rows.Add(r);
            currentAutoKey++;
            lbRowCount.Text = "SL Sản phẩm:" + stock.Rows.Count;

        }

        private void grid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                if (e.KeyCode == Keys.C)
                {
                    startSelectCell = false;
                    //MessageBox.Show("Ctr + C");
                    if (grid.CurrentCell != null)
                    {
                        if (grid.CurrentCell.Value != null)
                        {
                            string text = grid.CurrentCell.Value.ToString();
                            if (!string.IsNullOrWhiteSpace(text))
                            {
                                Clipboard.SetText(text);
                            }
                        }
                    }
                    return;
                }

                if (e.KeyCode == Keys.V)
                {
                    //MessageBox.Show("Ctr + V");
                    startSelectCell = false;
                    doPaste();
                    return;
                }

                return;
            }


            if (e.Shift)
            {
                if (e.KeyCode == Keys.Down && !startSelectCell)
                {
                    startSelectCell = true;
                    if (grid.CurrentCell.Value != null)
                    {
                        string text = grid.CurrentCell.Value.ToString();
                        startSelectPoint.X = grid.CurrentCell.RowIndex;
                        startSelectPoint.Y = grid.CurrentCell.ColumnIndex;
                        if (!string.IsNullOrWhiteSpace(text))
                        {
                            Clipboard.SetText(text);
                        }
                    }

                    return;
                }
            }


            if (e.KeyCode == Keys.Down)
            {
                if (grid.CurrentRow == null || grid.CurrentRow.Index == grid.RowCount - 1)
                {
                    newRow();
                }
            }
            else if (e.KeyCode == Keys.Enter && grid.CurrentCell != null)
            {
                Point p = grid.GetCellDisplayRectangle(grid.CurrentCell.ColumnIndex, grid.CurrentCell.RowIndex, false).Location;
                switch (grid.CurrentCell.ColumnIndex)
                {
                    case 3:
                        contextTypeMenu.Show(grid, p);
                        break;
                    case 4:
                        contextMenuGender.Show(grid, p);
                        break;
                }
                e.Handled = true;
            }
        }

        private void grid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }



            AutoCompleteStringCollection collection = getAutoCompleteCollectionByColumnIndex(e.ColumnIndex);
            stock.Rows[e.RowIndex].ClearErrors();
            if (e.ColumnIndex != clType.Index && collection != null && grid.CurrentCell != null && grid.CurrentCell.Value != null)
            {
                if (!string.IsNullOrWhiteSpace(grid.CurrentCell.Value.ToString()))
                {
                    collection.Add(grid.CurrentCell.Value.ToString());
                }
            }

            if (e.ColumnIndex == clType.Index && grid.CurrentCell != null && grid.CurrentCell.Value != null && !ignoreCellValueChanged)
            {
                string value = grid.CurrentCell.Value.ToString().ToLower();
                if (!typeMap.ContainsKey(value))
                {
                    MessageBox.Show("Loại không hợp lệ :" + value);
                    if (grid.CurrentRow.DefaultCellStyle.BackColor != Color.Red)
                    {
                        grid.CurrentRow.DefaultCellStyle.Tag = grid.CurrentRow.DefaultCellStyle.BackColor;
                    }

                    if (defaultCellColor == Color.Black)
                    {
                        defaultCellColor = grid.CurrentRow.DefaultCellStyle.BackColor;
                    }

                    grid.CurrentRow.DefaultCellStyle.BackColor = Color.Red;
                }
                else
                {
                    if (grid.CurrentRow.DefaultCellStyle.Tag != null)
                    {
                        grid.CurrentRow.DefaultCellStyle.BackColor = (Color)grid.CurrentRow.DefaultCellStyle.Tag;
                        grid.CurrentRow.DefaultCellStyle.Tag = null;
                    }
                    else
                    {
                        if (grid.CurrentRow.DefaultCellStyle.BackColor == Color.Red)
                        {
                            grid.CurrentRow.DefaultCellStyle.BackColor = defaultCellColor;
                        }
                    }
                }
            }

            if (e.ColumnIndex == gender.Index && grid.CurrentCell != null && grid.CurrentCell.Value != null && !ignoreCellValueChanged)
            {
                string value = grid.CurrentCell.Value.ToString().ToUpper();
                if (!value.Equals("T") && !value.Equals("G"))
                {
                    MessageBox.Show("Giới tính không hợp lệ");
                    grid.CurrentRow.DefaultCellStyle.Tag = grid.CurrentRow.DefaultCellStyle.BackColor;
                    grid.CurrentRow.DefaultCellStyle.BackColor = Color.Red;
                }
                else
                {
                    if (grid.CurrentRow.DefaultCellStyle.Tag != null)
                    {
                        grid.CurrentRow.DefaultCellStyle.BackColor = (Color)grid.CurrentRow.DefaultCellStyle.Tag;
                        grid.CurrentRow.DefaultCellStyle.Tag = null;
                    }
                    else
                    {
                        if (grid.CurrentRow.DefaultCellStyle.BackColor == Color.Red)
                        {
                            grid.CurrentRow.DefaultCellStyle.BackColor = defaultCellColor;
                        }
                    }
                }
            }
        }


        private void doPaste()
        {
            string text = Clipboard.GetText();
            if (grid.CurrentCell != null)
            {
                grid.CurrentCell.Value = text;
            }
        }

        private void mnCheckCost_CheckedChanged(object sender, EventArgs e)
        {
            cost.Visible = mnCheckCost.Checked;
        }

        private void mnCheckGiasi_CheckedChanged(object sender, EventArgs e)
        {
            giasi.Visible = mnCheckGiasi.Checked;
        }

        private void mnCheckCost_Click(object sender, EventArgs e)
        {
            mnCheckCost.Checked = !mnCheckCost.Checked;
        }

        private void mnCheckGiasi_Click(object sender, EventArgs e)
        {
            mnCheckGiasi.Checked = !mnCheckGiasi.Checked;
        }

        private void btNew_Click(object sender, EventArgs e)
        {
            grid.Enabled = true;
            if (!loadSupplierAndColor)
            {
                Database.loadSupplierAndColorCollection();
                loadSupplierAndColor = true;
            }

            newRow();
        }

        private void grid_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {

            // Load context menu on right mouse click
            DataGridView.HitTestInfo hitTestInfo;
            if (e.Button == MouseButtons.Right)
            {
                try
                {
                    hitTestInfo = grid.HitTest(e.X, e.Y);
                    // If column is first column
                    if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 3)
                        contextTypeMenu.Show(grid, new Point(e.X, e.Y));
                    // If column is second column
                    if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 1)
                        contextTypeMenu.Show(grid, new Point(e.X, e.Y));
                }
                catch (Exception ee)
                {
                    Reporter.WriteErrorEx(ee);
                }
            }
        }

        private void contextTypeMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            grid.CurrentCell.Value = e.ClickedItem.Text;
        }

        private void contextMenuGender_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            grid.CurrentCell.Value = e.ClickedItem.Text;
        }

        private void grid_KeyUp(object sender, KeyEventArgs e)
        {
            if (startSelectCell && !e.Shift)
            {
                startSelectCell = false;
                string value = null;
                if (grid[startSelectPoint.Y, startSelectPoint.X].Value != null)
                {
                    value = grid[startSelectPoint.Y, startSelectPoint.X].Value.ToString();
                }
                if (value == null)
                {
                    startSelectPoint = new Point(0, 0);
                    return;
                }

                int r = grid.CurrentRow.Index;
                //grid.BeginEdit(true);
                ignoreCellValueChanged = true;
                for (int i = startSelectPoint.X + 1; i <= r; i++)
                {
                    grid[startSelectPoint.Y, i].Value = value;
                }

                ignoreCellValueChanged = false;
                grid.CommitEdit(DataGridViewDataErrorContexts.Commit);

                startSelectPoint = new Point(0, 0);
            }
            else if (char.IsLetter((char)e.KeyCode))
            {
                if (grid.CurrentCell.ColumnIndex == clType.Index)
                {
                    Point p = grid.GetCellDisplayRectangle(grid.CurrentCell.ColumnIndex, grid.CurrentCell.RowIndex, false).Location;
                    contextTypeMenu.Show(grid, p);
                }
                else if (grid.CurrentCell.ColumnIndex == gender.Index)
                {
                    Point p = grid.GetCellDisplayRectangle(grid.CurrentCell.ColumnIndex, grid.CurrentCell.RowIndex, false).Location;
                    contextMenuGender.Show(grid, p);
                }
            }
        }

        private void grid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                try
                {
                    grid.Rows.Remove(grid.CurrentRow);
                    currentAutoKey = lastAutoKey;
                    foreach (DataRow r in stock.Rows)
                    {
                        r["autoKey"] = currentAutoKey;
                        currentAutoKey++;
                    }

                    lbRowCount.Text = "SL Sản phẩm:" + stock.Rows.Count;
                }
                catch (Exception ee)
                {
                    Reporter.WriteErrorEx(ee);
                }

            }
        }

        public override void FormActived()
        {
            base.FormActived();
            string connectionString = RuntimeData.GetDBBranchConnection(listBranch.Text);
            if (!string.IsNullOrEmpty(connectionString))
            {
                DBBranchConnection.ConnectionString = connectionString;
            }
        }

        private void doSave()
        {
            string connectionString = RuntimeData.GetDBBranchConnection(listBranch.Text);
            if (!string.IsNullOrEmpty(connectionString))
            {
                DBBranchConnection.ConnectionString = connectionString;
            }
            grid.CommitEdit(DataGridViewDataErrorContexts.Commit);
            grid.EndEdit();
            DataRowCollection changedRows = stock.Rows;
            ArrayList sqlBuilder = new ArrayList();
            string sqlUpdateFormat = "insert into shop_stock(`autoKey`,`itemId`,`itemName`,`type`,`amount`,`gender`,`size`,`color`,`cost`,`price`,`giasi`,`supplier`,`createTime`, `branch`) " +
                " values({0},'{1}','{2}',{3},{4},'{5}','{6}','{7}',{8},{9},{10},'{11}','" + DateTime.Now.ToString("yyyy-MM-dd") + "', 0) on duplicate key update `itemName`='{2}', `type`= {3}, `amount`={4}, `gender`='{5}', `size`='{6}',`color`='{7}',`cost`={8},`price`={9},`giasi`={10},`supplier`='{11}';";

            int count = 0;
            foreach (DataRow r in changedRows)
            {
                int typeId = 0;
                r.ClearErrors();
                if (r["itemName"] == null || string.IsNullOrEmpty(r["itemName"].ToString()))
                {
                    r.SetColumnError("itemName", "Tên sản phẩm không hợp lệ");
                    continue;
                }else if (r["gender"] == null || string.IsNullOrEmpty(r["gender"].ToString())) 
                {
                    r.SetColumnError("gender", "Giới tính không hợp lệ");
                    continue;
                }

                if (r["type"] != null && typeMap.ContainsKey(r["type"].ToString()))
                {
                    count++;
                    typeId = typeMap[r["type"].ToString()];
                    string itemId = createItemId(r["type"].ToString(), r["gender"].ToString(), Int32.Parse(r["autoKey"].ToString()));
                    //txtSql.Text += string.Format(sqlUpdateFormat, r["autoKey"], r["itemId"], r["itemName"], typeId, r["amount"], r["gender"], r["size"], r["color"], r["cost"], r["price"], r["giasi"], r["supplier"]);
                    string itemName = r["itemName"].ToString();
                    itemName = itemName.Replace("'", "");

                    string supplier = r["supplier"].ToString();
                    supplier = supplier.Replace("'", "");

                    string size = r["size"].ToString();
                    size = size.Replace("'", "");

                    string color = r["color"].ToString();
                    color = color.Replace("'", "");

                    int numer = Int32.Parse(r["amount"].ToString());
                    sqlBuilder.Add(string.Format(sqlUpdateFormat, r["autoKey"], itemId, itemName, typeId, numer, r["gender"], size, color, r["cost"], r["price"], r["giasi"], supplier));
                    r["isOk"] = "true";
                }                
                else
                {
                    r["isOk"] = "false";
                    if (r["type"] != null)
                    {
                        r.SetColumnError("type", "Loại không đúng");
                    }
                    continue;
                }

            }

            if (count > 0)
            {
                if (DataManager.BranchExecuteQuerys(sqlBuilder, null) == -1)
                {
                    string fileName = DateTime.Now.ToString("MM-dd") + "-" + Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".xml";
                    string filePath = Path.Combine(BackupUtil.doCheckWorkspace(), fileName);
                    stock.WriteXml(filePath, System.Data.XmlWriteMode.WriteSchema);
                    return;
                }

                if (count == stock.Rows.Count)
                {
                    stock.Rows.Clear();
                }
                else
                {
                    for (int i = changedRows.Count; --i >= 0; )
                    {
                        if (changedRows[i]["isOk"].Equals("true"))
                        {
                            changedRows[i].Delete();
                        }
                    }
                    doCheckDataOnGrid();
                }
                lastAutoKey = DataManager.BranchGetLastItemIdInStock();
                if (lastAutoKey > 0)
                {
                    lastAutoKey++;
                    currentAutoKey = lastAutoKey;
                }
            }
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            try
            {
                doSave();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void doCheckDataOnGrid()
        {
            foreach (DataGridViewRow r in grid.Rows)
            {
                bool isError = false;
                if (r.Cells[clType.Index].Value == null)
                {
                    isError = true;
                }
                else
                {
                    string typeName = r.Cells[clType.Index].Value.ToString();
                    typeName = typeName.ToLower();
                    if (!typeMap.ContainsKey(typeName))
                    {
                        isError = true;
                    }
                }

                if (isError)
                {
                    if (grid.CurrentRow.DefaultCellStyle.BackColor != Color.Red)
                    {
                        grid.CurrentRow.DefaultCellStyle.Tag = grid.CurrentRow.DefaultCellStyle.BackColor;
                    }

                    if (defaultCellColor == Color.Black)
                    {
                        defaultCellColor = grid.CurrentRow.DefaultCellStyle.BackColor;
                    }

                    grid.CurrentRow.DefaultCellStyle.BackColor = Color.Red;
                }
                else
                {
                    if (grid.CurrentRow.DefaultCellStyle.Tag != null)
                    {
                        grid.CurrentRow.DefaultCellStyle.BackColor = (Color)grid.CurrentRow.DefaultCellStyle.Tag;
                        grid.CurrentRow.DefaultCellStyle.Tag = null;
                    }
                    else
                    {
                        if (grid.CurrentRow.DefaultCellStyle.BackColor == Color.Red)
                        {
                            grid.CurrentRow.DefaultCellStyle.BackColor = defaultCellColor;
                        }
                    }
                }
            }
        }


        private string createItemId(string typeName, string gender, int itemId)
        {
            string name = typeName.ToUpper();
            string prefix = name.Substring(0, 1);
            if (prefix.Equals("Á") || prefix.Equals("Â") || prefix.Equals("Ă") || prefix.Equals("Ắ") || prefix.Equals("Ấ"))
            {
                prefix = "A";
            }
            else if (prefix.Equals("Đ"))
            {
                prefix = "D";
            }
            else if (prefix.Equals("É") || prefix.Equals("Ê") || prefix.Equals("Ế") || prefix.Equals("Ề") || prefix.Equals("Ễ") || prefix.Equals("Ệ") || prefix.Equals("Ể"))
            {
                prefix = "E";
            }
            else if (prefix.Equals("Ú") || prefix.Equals("Ù") || prefix.Equals("Ứ") || prefix.Equals("Ư"))
            {
                prefix = "U";
            }
            else if (prefix.Equals("Ô") || prefix.Equals("Ồ") || prefix.Equals("Ố"))
            {
                prefix = "O";
            }

            return prefix + gender + itemId;
        }

        private void btOpen_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.InitialDirectory = BackupUtil.doCheckWorkspace();
                if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    string filePath = dlg.FileName;
                    stock.Clear();
                    stock.ReadXml(filePath);

                    lastAutoKey = DataManager.BranchGetLastItemIdInStock();
                    if (lastAutoKey >= 0)
                    {
                        lastAutoKey += 1;
                    }
                    currentAutoKey = lastAutoKey;
                    foreach (DataRow r in stock.Rows)
                    {
                        r["autoKey"] = currentAutoKey;
                        currentAutoKey++;
                    }

                    lbRowCount.Text = "SL Sản phẩm:" + stock.Rows.Count;
                    bindingSource.ResetBindings(true);

                    grid.Enabled = true;
                    if (!loadSupplierAndColor)
                    {
                        Database.loadSupplierAndColorCollection();
                        loadSupplierAndColor = true;
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void grid_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow r = grid.Rows[e.RowIndex];
            r.Cells[cost.Index].Style.ForeColor = Color.White;
        }

        private void grid_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow r = grid.Rows[e.RowIndex];
            r.Cells[cost.Index].Style.ForeColor = Color.Black;
        }

        private void grid_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == clType.Index || e.ColumnIndex == gender.Index)
            {
                try
                {


                }
                catch (Exception ex)
                {
                    Reporter.WriteErrorEx(ex);
                }

            }

        }

        private void grid_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.ColumnIndex == price.Index
                || e.ColumnIndex == cost.Index
                || e.ColumnIndex == amount.Index)
            {
                e.Cancel = true;
                grid[e.ColumnIndex, e.RowIndex].Value = 0;
                if (e.ColumnIndex == amount.Index)
                {
                    grid[e.ColumnIndex, e.RowIndex].Value = 1;
                }
            }
        }

        private void listBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            LockWaitOrRelease(true);
            btConnect.Enabled = true;
        }

        private void LockWaitOrRelease(bool isLock)
        {
            this.listBranch.Enabled = !isLock;
            this.grid.Enabled = !isLock;
            this.btSave.Enabled = !isLock;
            this.btOpen.Enabled = !isLock;
            this.btNew.Enabled = !isLock;
        }

        private void btConnect_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(listBranch.Text))
            {
                return;
            }

            this.Enabled = false;
            try
            {
                this.UseWaitCursor = true;
                string connectionString = RuntimeData.GetDBBranchConnection(listBranch.Text);
                if (string.IsNullOrEmpty(connectionString))
                {
                    MessageBox.Show(this, string.Format("Không thể kết nối tới [{0}]", listBranch.Text), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                DBBranchConnection.ConnectionString = connectionString;
                if (DBBranchConnection.TestConnection())
                {
                    PlayCompleteSound();
                    // Load data here :
                    lastAutoKey = DataManager.BranchGetLastItemIdInStock();
                    if (lastAutoKey >= 0)
                    {
                        lastAutoKey += 1;
                        currentAutoKey = lastAutoKey;
                        stock.Rows.Clear();
                    }
                    else
                    {
                        MessageBox.Show("Có lỗi trong quá trình kết nối với CSLD");
                        this.Close();
                    }
                    //
                    MessageBox.Show(this, string.Format("Kết nối thành công tới chi nhánh [{0}]", listBranch.Text), "Thông báo", MessageBoxButtons.OK);

                }
                else
                {
                    MessageBox.Show(this, string.Format("Không thể kết nối tới [{0}]", listBranch.Text), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                this.Enabled = true;
                this.UseWaitCursor = false;
                LockWaitOrRelease(false);
                grid.Focus();
            }
        }

        private void PlayCompleteSound()
        {
            try
            {
                this.sound.PlaySync();
            }
            catch (Exception e)
            {
            }
        }
    }
}
